<template>
  <div class="favorite-list-page">
    <div class="container">
      <div class="page-header">
        <h1>我的收藏</h1>
        <div class="page-actions">
          <el-button
            v-if="selectedItems.length > 0"
            type="danger"
            @click="handleBatchDelete"
          >
            批量删除 ({{ selectedItems.length }})
          </el-button>
          <el-button @click="toggleSelectMode">
            {{ isSelectMode ? '取消' : '管理' }}
          </el-button>
        </div>
      </div>

      <div class="filter-section">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="商家" name="merchant" />
          <el-tab-pane label="服务" name="service" />
        </el-tabs>
      </div>

      <div class="favorite-list" v-loading="loading">
        <div v-if="favorites.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无收藏内容">
            <el-button type="primary" @click="goToHome">去首页看看</el-button>
          </el-empty>
        </div>

        <div
          v-for="item in favorites"
          :key="`${item.type}-${item.id}`"
          class="favorite-item"
          :class="{ 'selected': selectedItems.includes(item.id) }"
        >
          <div class="item-checkbox" v-if="isSelectMode">
            <el-checkbox
              :model-value="selectedItems.includes(item.id)"
              @change="handleItemSelect(item.id, $event)"
            />
          </div>
          
          <div class="item-image" @click="handleItemClick(item)">
            <el-image
              :src="item.image || '/default-image.jpg'"
              fit="cover"
              :lazy="true"
            />
            <div class="item-type-badge">
              <el-tag :type="item.type === 'merchant' ? 'primary' : 'success'" size="small">
                {{ item.type === 'merchant' ? '商家' : '服务' }}
              </el-tag>
            </div>
          </div>

          <div class="item-content" @click="handleItemClick(item)">
            <div class="item-header">
              <h3 class="item-title">{{ item.title }}</h3>
              <div class="item-rating" v-if="item.rating">
                <el-rate
                  :model-value="item.rating"
                  disabled
                  size="small"
                  show-score
                />
              </div>
            </div>

            <p class="item-description">{{ item.description }}</p>

            <div class="item-meta">
              <div class="meta-info">
                <span class="price" v-if="item.price">
                  ¥{{ item.price }}起
                </span>
                <span class="location" v-if="item.location">
                  <el-icon><Location /></el-icon>
                  {{ item.location }}
                </span>
                <span class="stats" v-if="item.stats">
                  {{ item.stats }}
                </span>
              </div>
              <div class="item-time">
                {{ formatDate(item.createdAt) }}
              </div>
            </div>
          </div>

          <div class="item-actions">
            <el-button
              type="danger"
              link
              @click="handleDelete(item)"
              v-if="!isSelectMode"
            >
              取消收藏
            </el-button>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore && !loading">
        <el-button @click="loadMore" :loading="loadingMore">
          加载更多
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Location } from '@element-plus/icons-vue'
import { favoriteApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const favorites = ref([])
const loading = ref(true)
const loadingMore = ref(false)
const activeTab = ref('all')
const isSelectMode = ref(false)
const selectedItems = ref([])
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)

// 生命周期
onMounted(() => {
  fetchFavorites()
})

// 方法定义
const fetchFavorites = async (reset = true) => {
  try {
    if (reset) {
      loading.value = true
      page.value = 1
    } else {
      loadingMore.value = true
    }

    const response = await favoriteApi.getFavoriteList({
      type: activeTab.value === 'all' ? undefined : activeTab.value,
      page: page.value,
      pageSize: pageSize.value
    })

    const { data, total } = response.data
    
    if (reset) {
      favorites.value = data
    } else {
      favorites.value.push(...data)
    }

    hasMore.value = favorites.value.length < total
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  selectedItems.value = []
  fetchFavorites()
}

const toggleSelectMode = () => {
  isSelectMode.value = !isSelectMode.value
  selectedItems.value = []
}

const handleItemSelect = (id, checked) => {
  if (checked) {
    selectedItems.value.push(id)
  } else {
    const index = selectedItems.value.indexOf(id)
    if (index > -1) {
      selectedItems.value.splice(index, 1)
    }
  }
}

const handleItemClick = (item) => {
  if (isSelectMode.value) return
  
  if (item.type === 'merchant') {
    router.push(`/merchants/${item.targetId}`)
  } else if (item.type === 'service') {
    router.push(`/services/${item.targetId}`)
  }
}

const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消收藏"${item.title}"吗？`,
      '取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await favoriteApi.removeFavorite(item.type, item.targetId)
    ElMessage.success('取消收藏成功')
    fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要取消选中的 ${selectedItems.value.length} 个收藏吗？`,
      '批量取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await favoriteApi.batchRemoveFavorites(selectedItems.value)
    ElMessage.success('批量取消收藏成功')
    selectedItems.value = []
    isSelectMode.value = false
    fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消收藏失败:', error)
      ElMessage.error('批量取消收藏失败')
    }
  }
}

const loadMore = () => {
  page.value++
  fetchFavorites(false)
}

const goToHome = () => {
  router.push('/home')
}

const formatDate = (date) => {
  return dayjs(date).format('MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.favorite-list-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }

  .page-actions {
    display: flex;
    gap: 12px;
  }
}

.filter-section {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }
}

.favorite-list {
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }
}

.favorite-item {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;

  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  &.selected {
    border-color: #409eff;
    background-color: #f0f9ff;
  }

  .item-checkbox {
    margin-right: 12px;
    display: flex;
    align-items: flex-start;
    padding-top: 8px;
  }

  .item-image {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    overflow: hidden;
    margin-right: 16px;
    flex-shrink: 0;
    position: relative;

    .el-image {
      width: 100%;
      height: 100%;
    }

    .item-type-badge {
      position: absolute;
      top: 8px;
      left: 8px;
    }
  }

  .item-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 120px;

    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;

      .item-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
        line-height: 1.4;
      }

      .item-rating {
        margin-left: 12px;
        flex-shrink: 0;
      }
    }

    .item-description {
      margin: 0 0 auto 0;
      color: #666;
      font-size: 14px;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .item-meta {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-top: 12px;

      .meta-info {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        align-items: center;

        .price {
          color: #e6a23c;
          font-weight: 600;
          font-size: 16px;
        }

        .location {
          display: flex;
          align-items: center;
          color: #666;
          font-size: 12px;

          .el-icon {
            margin-right: 4px;
          }
        }

        .stats {
          color: #999;
          font-size: 12px;
        }
      }

      .item-time {
        color: #999;
        font-size: 12px;
        white-space: nowrap;
      }
    }
  }

  .item-actions {
    display: flex;
    align-items: flex-start;
    padding-top: 8px;
    margin-left: 12px;
  }
}

.load-more {
  text-align: center;
  margin-top: 24px;
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;

    h1 {
      text-align: center;
    }

    .page-actions {
      justify-content: center;
    }
  }

  .filter-section {
    padding: 0 10px;
  }

  .favorite-item {
    flex-direction: column;
    padding: 12px;

    .item-checkbox {
      position: absolute;
      top: 12px;
      right: 12px;
      margin: 0;
    }

    .item-image {
      width: 100%;
      height: 200px;
      margin-right: 0;
      margin-bottom: 12px;
    }

    .item-content {
      min-height: auto;

      .item-header {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;

        .item-rating {
          margin-left: 0;
          align-self: flex-start;
        }
      }

      .item-meta {
        flex-direction: column;
        align-items: stretch;
        gap: 8px;

        .meta-info {
          flex-wrap: wrap;
        }

        .item-time {
          align-self: flex-end;
        }
      }
    }

    .item-actions {
      margin-left: 0;
      margin-top: 12px;
      justify-content: center;
    }
  }
}
</style> 